#include <iostream>
#include <string>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>

enum class Status // C++11 强类型枚举
{
    NEW,          // 新建状态， 就是单纯的连接
    CONNECTING,   // 正在连接， 仅仅方便查询 conn 状态
    CONNECTED,    // 连接或者重连成功
    DISCONNECTED, // 重连失败
    CLOSED        // 连接失败， 经历重连， 无法连接
};

enum ExitCode
{
    USAGE_ERR = 1,
    SOCKET_ERR
};

void Usage(const std::string &process)
{
    std::cout << "Usage: " << process << " server_ip server_port" << std::endl;
}

class ClientConnection
{
public:
    ClientConnection(const uint16_t serverport, const std::string &serverip)
        : _sockfd(-1),
          _serverport(serverport),
          _serverip(serverip),
          _retry_interval(1),
          _max_retries(5),
          _status(Status::NEW)
    {
    }

    void Connect()
    {
        _sockfd = ::socket(AF_INET, SOCK_STREAM, 0);
        if (_sockfd == 0)
        {
            std::cerr << "socket create error" << std::endl;
            exit(ExitCode::SOCKET_ERR);
        }

        sockaddr_in server;
        memset(&server, 0, sizeof(server));
        server.sin_family = AF_INET;
        server.sin_port = ::htons(_serverport);
        ::inet_pton(AF_INET, _serverip.c_str(), &server.sin_addr);

        int n = ::connect(_sockfd, (sockaddr *)&server, sizeof(server));
        if (n < 0)
        {
            // 1. 关闭sockfd
            Disconnect();
            // 2. 更新状态
            _status = Status::DISCONNECTED;
            // 3. 返回
            return;
        }
        _status = Status::CONNECTED;
    }

    void Reconnect()
    {
        int cnt = 0;
        while (true)
        {
            _status = Status::CONNECTING;
            Connect();
            if (_status == Status::CONNECTED)
            {
                break;
            }
            cnt++;
            if (cnt > _max_retries)
            {
                _status = Status::CLOSED;
                std::cout << "重连失败，请检查你的网络设置" << std::endl;
                break;
            }
            std::cout << "断线重连中，重连次数：" << cnt << std::endl;
            sleep(_retry_interval);
        }
    }

    void Process() // 正常的IO通信
    {
        while (true)
        {
            std::string message;
            std::cin >> message;
            ssize_t n = send(_sockfd, message.c_str(), sizeof(message), 0);
            if (n > 0)
            {
                char buffer[1024];
                ssize_t m = recv(_sockfd, buffer, sizeof(buffer), 0);
                if (m > 0)
                {
                    buffer[m] = 0;
                    std::cout << "server echo# " << buffer << std::endl;
                }
                else
                {
                    _status = Status::DISCONNECTED;
                    break;
                }
            }
            else
            {
                std::cerr << "send error" << std::endl;
                _status = Status::CLOSED;
                break;
            }
        }
    }

    void Disconnect()
    {
        if (_sockfd > -1)
        {
            close(_sockfd);
            _sockfd = -1;
            _status = Status::CLOSED;
        }
    }

    Status GetStatus()
    {
        return _status;
    }

    ~ClientConnection()
    {
    }

private:
    int _sockfd;
    uint16_t _serverport;  // server port 端口号
    std::string _serverip; // server ip 地址
    int _retry_interval;   // 重试时间间隔
    int _max_retries;      // 重试次数
    Status _status;        // 连接状态
};

class TcpClient
{
public:
    TcpClient(const uint16_t serverport, const std::string &serverip)
        : _conn(serverport, serverip)
    {
    }

    void Execute()
    {
        while (true)
        {
            switch (_conn.GetStatus())
            {
            case Status::NEW:
                _conn.Connect();
                break;
            case Status::CONNECTED:
                std::cout << "连接成功, 开始进行通信... " << std::endl;
                _conn.Process();
                break;
            case Status::DISCONNECTED:
                std::cout << "连接失败或者对方掉线， 开始重连... " << std::endl;
                _conn.Reconnect();
                break;
            case Status::CLOSED:
                _conn.Disconnect();
                std::cout << "重连失败, 退出... " << std::endl;
                return; // 退出
            default:
                break;
            }
        }
    }

    ~TcpClient()
    {
    }

private:
    ClientConnection _conn;
};

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(ExitCode::USAGE_ERR);
    }

    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);

    TcpClient client(serverport, serverip);
    client.Execute();

    return 0;
}